<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./css/common.css">
    <link rel="stylesheet" href="./css/connect/index.css">
    <title>连接</title>
    <script type="text/javascript" src="https://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/vconsole/2.5.1/vconsole.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>

<body>
    <div id="app">
        <div class="connect-content">
            <div class="connect-content__middle">
                <div class="connect-title">发现云康宝体脂称</div>
                <img src="./img/iconsA.png" alt="">
                <div class="text">{{connectSuccess}}</div>
            </div>
        </div>
        <div class="connect-mask" id="mask" v-if="mask"></div>
        <div class="connect-progress" v-if="progress">
            <span class="inner-text" id="innerText">{{successfulRegister}}</span>
            <span class="inner-progress" id="pro">{{Math.floor(barWidth)}}%</span>
            <div class="inner-bar">
                <span class="bar-color" :style="{'width': barWidth + '%'}" id="bar"></span>
            </div>
        </div>
        <transition name="fade">
            <div class="connect-alert" v-show="alerts">
                <div>
                    <h3>提示</h3>
                </div>
                <div>{{alertsMessage}}</div>
                <div class="connect-alert-btn" @click='aler'>确定</div>
            </div>
        </transition>
        <div class="fide" v-show='alerts'></div>
    </div>
</body>
<script>
    const UUID_IBT_SERVICES = "0000FFE0-0000-1000-8000-00805F9B34FB"
    const UUID_IBT_READ = "0000FFE1-0000-1000-8000-00805F9B34FB"
    const UUID_IBT_WRITE = "0000FFE3-0000-1000-8000-00805F9B34FB"

    class ConnectDecoder {


        constructor(lisenter) {
            this.hasConnect = false
            this.hasGotMac = false
            if (window.hilink) {
                window.onGetCurrentUnregisteredDevice = this.onGetCurrentUnregisteredDevice.bind(this)
                window.onBLEConnectionStateChange = this.onBLEConnectionStateChange.bind(this)
                window.onBLECharacteristicValueChange = this.onBLECharacteristicValueChange.bind(this)
                window.onBluetoothAdapterStateChange = this.onBluetoothAdapterStateChange.bind(this)
                window.onRegisterBleDevice = this.onRegisterBleDevice.bind(this)
                window.onWriteCallback = this.onWriteCallback.bind(this)


                hilink.getCurrentUnregisteredDevice("onGetCurrentUnregisteredDevice")
            }
            this.lisenter = lisenter
        }

        onGetCurrentUnregisteredDevice(deviceString) {
            console.log("获取设备", deviceString)
            this.device = JSON.parse(deviceString)

            hilink.getBluetoothAdapterState("onBluetoothAdapterStateChange")

        }

        onBluetoothAdapterStateChange(json) {
            var status = JSON.parse(json)
            if (status.available && !this.hasConnect) {
                this.hasConnect = true
                hilink.onBLEConnectionStateChange("onBLEConnectionStateChange")
                hilink.createBLEConnection(this.device.deviceId)
            } else if (!status.available) {
                //蓝牙未打开，请求打开蓝牙
                hilink.openBluetoothAdapter()
            }
        }

        onRegisterBleDevice(deviceString) {
            console.log("注册结果", deviceString)
            this.lisenter.onRegisterCallback(deviceString)
        }


        onBLEConnectionStateChange(deviceString) {

            const device = JSON.parse(deviceString)
            console.log("连接状态变化", device)

            if (device.connected) {
                setTimeout(() => {
                    console.log("定时器调用成功")
                    hilink.notifyBLECharacteristicValueChange(device.deviceId, UUID_IBT_SERVICES,
                        UUID_IBT_READ,
                        true)
                }, 1500)
                hilink.onBLECharacteristicValueChange("onBLECharacteristicValueChange")
                console.log("连接成功", device)
            } else {
                this.hasConnect = false
                this.lisenter.onConnectFail
                console.log("连接断开", device)
            }

        }

        onBLECharacteristicValueChange(jsonData) {
            var _data = JSON.parse(jsonData)
            var hexString = _data.data
            var deviceId = _data.deviceId
            var data = []
            for (var i = 0; i < hexString.length; i += 2) {
                var str = hexString.substring(i, i + 2)
                var itemByte = parseInt(str, 16);
                data.push(itemByte)
            }

            console.log("收到数据", hexString)
            this.decode.bind(this)(data)
        }

        toHex(i) {
            var str = i.toString(16).toUpperCase()
            if (i < 16) {
                str = '0' + str
            }
            return str
        }

        decode(data) {
            var scaleType = data[2];
            switch (data[0]) {
                case 0x12:
                    {
                        if (this.hasGotMac) {
                            return
                        }
                        this.hasGotMac = true

                        var deviceId = this.toHex(data[8]) + ":" + this.toHex(data[7]) + ":" + this.toHex(data[6]) +
                            ":" + this.toHex(data[5]) + ":" + this.toHex(data[4]) + ":" + this.toHex(data[3])
                        var fwv = data[9]
                        var hwv = data[11]
                        console.log("listenrer", this.lisenter.onGetResisterInfo)
                        this.lisenter.onGetResisterInfo({
                            deviceId,
                            fwv,
                            hwv
                        })
                        const sendCmd = this.buildCmd(0x13, scaleType, 0x01, 0x10, 0x00, 0x00, 0x00);

                        console.log("发送数据", sendCmd)

                        this.writeData(this.device.deviceId, sendCmd)

                        break;
                    }

            }
        }
        arrayToHexString(data) {
            let str = "";

            data.forEach((item) => {
                const s = item.toString(16)
                if (s.length > 1) {
                    str += s
                } else {
                    str += '0' + s
                }
            });
            return str.toUpperCase()
        }

        writeData(deviceId, cmd) {
            hilink.writeBLECharacteristicValue(deviceId, UUID_IBT_SERVICES, UUID_IBT_WRITE, cmd,
                "onWriteCallback")
        }

        onWriteCallback(data) {
            console.log('写入数据回调', data)
        }

        buildCmd(cmd, deviceType, ...data) {
            const cmdData = [cmd, data.length + 4, deviceType];
            let checksum = 0;
            cmdData.push(...data);
            cmdData.forEach((item) => checksum += item);
            checksum = checksum & 0xFF;
            cmdData.push(checksum);

            let str = this.arrayToHexString(cmdData)

            console.log(str);

            return str;

        }
    }

    var app = new Vue({
        el: '#app',
        data: {
            barWidth: 0,
            connectSuccess: '正在注册设备...',
            mask: true,
            progress: true,
            successfulRegister: '正在努力注册设备，请稍后...',
            isRegister: false,
            timeoutCount: 0, // 超时记时数
            timerTimeout: null, // 超时定时器
            alerts: false,
            alertsMessage: ''
        },
        created() {
            this.decoder = new ConnectDecoder(this)
        },
        mounted() {
            this.bar()
            this.timeoutFun()
        },
        methods: {
            //提示框
            aler() {
                this.alerts = !this.alerts
                try {
                    hilink.finishDeviceActivity()
                } catch (err) {
                    console.log('蓝牙设备未连接')
                }
            },
            bar() { // 进度条
                var timer = setInterval(() => {
                    var _this = this
                    _this.barWidth += 0.3
                    if (_this.barWidth >= 90) {
                        clearInterval(timer)
                        timer = null
                    }
                }, 30)
            },
            onRegisterCallback(res) { // windows全局注册回调函数
                var _this = this
                res = JSON.parse(res)
                console.info('注册返回值', res)
                if (+res.errCode === 0) {
                    console.log('zjw-register4-注册成功', res.errCode)
                    _this.successfulRegister = '恭喜你,注册成功!'
                    _this.connectSuccess = '连接成功!'
                    clearInterval(_this.timerTimeout);
                    _this.timerTimeout = null
                    setTimeout(() => {
                        _this.mask = false
                        _this.progress = false
                    }, 1000)
                } else if (+res.errCode === 90012) {
                    _this.alertsMessage = '设备已注册'
                    _this.alerts = true
                } else {
                    _this.alertsMessage = '设备未连接'
                    _this.alerts = true
                }
            },

            onGetResisterInfo(datas) {
                var _this = this
                if (!_this.isRegister) {
                    _this.isRegister = true
                    _this.registerDeviceFun(datas.deviceId, datas.fwv, datas.hwv)

                }
            },

            onConnectFail() {
                var _this = this
                _this.timerTimeout = null
                _this.alertsMessage = '连接失败，请重试'
                _this.alerts = true
            },
            registerDeviceFun(deviceId, fwv, hwv) { // 注册蓝牙
                try {
                    window.hilink.registerBleDevice(deviceId, fwv, hwv, 'onRegisterBleDevice')
                } catch (e) {
                    console.warn('注册蓝牙失败')
                }
            },
            timeoutFun() {
                var _this = this
                _this.timerTimeout = setInterval(() => {
                    _this.timeoutCount++
                        if (_this.timeoutCount > 90) {
                            clearInterval(_this.timerTimeout)
                            _this.timerTimeout = null
                            _this.alertsMessage = '连接超时,请重试'
                            _this.alerts = true
                        }
                }, 1000)
            }
        }
    })

</script>

</html>
